loaders.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. """API and implementations for loading templates from different data
  2. sources.
  3. """
  4. import importlib.util
  5. import os
  6. import posixpath
  7. import sys
  8. import typing as t
  9. import weakref
  10. import zipimport
  11. from collections import abc
  12. from hashlib import sha1
  13. from importlib import import_module
  14. from types import ModuleType
  15. from .exceptions import TemplateNotFound
  16. from .utils import internalcode
  17. from .utils import open_if_exists
  18. if t.TYPE_CHECKING:
  19. from .environment import Environment
  20. from .environment import Template
  21. def split_template_path(template: str) -> t.List[str]:
  22. """Split a path into segments and perform a sanity check. If it detects
  23. '..' in the path it will raise a `TemplateNotFound` error.
  24. """
  25. pieces = []
  26. for piece in template.split("/"):
  27. if (
  28. os.path.sep in piece
  29. or (os.path.altsep and os.path.altsep in piece)
  30. or piece == os.path.pardir
  31. ):
  32. raise TemplateNotFound(template)
  33. elif piece and piece != ".":
  34. pieces.append(piece)
  35. return pieces
  36. class BaseLoader:
  37. """Baseclass for all loaders. Subclass this and override `get_source` to
  38. implement a custom loading mechanism. The environment provides a
  39. `get_template` method that calls the loader's `load` method to get the
  40. :class:`Template` object.
  41. A very basic example for a loader that looks up templates on the file
  42. system could look like this::
  43. from jinja2 import BaseLoader, TemplateNotFound
  44. from os.path import join, exists, getmtime
  45. class MyLoader(BaseLoader):
  46. def __init__(self, path):
  47. self.path = path
  48. def get_source(self, environment, template):
  49. path = join(self.path, template)
  50. if not exists(path):
  51. raise TemplateNotFound(template)
  52. mtime = getmtime(path)
  53. with open(path) as f:
  54. source = f.read()
  55. return source, path, lambda: mtime == getmtime(path)
  56. """
  57. #: if set to `False` it indicates that the loader cannot provide access
  58. #: to the source of templates.
  59. #:
  60. #: .. versionadded:: 2.4
  61. has_source_access = True
  62. def get_source(
  63. self, environment: "Environment", template: str
  64. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  65. """Get the template source, filename and reload helper for a template.
  66. It's passed the environment and template name and has to return a
  67. tuple in the form ``(source, filename, uptodate)`` or raise a
  68. `TemplateNotFound` error if it can't locate the template.
  69. The source part of the returned tuple must be the source of the
  70. template as a string. The filename should be the name of the
  71. file on the filesystem if it was loaded from there, otherwise
  72. ``None``. The filename is used by Python for the tracebacks
  73. if no loader extension is used.
  74. The last item in the tuple is the `uptodate` function. If auto
  75. reloading is enabled it's always called to check if the template
  76. changed. No arguments are passed so the function must store the
  77. old state somewhere (for example in a closure). If it returns `False`
  78. the template will be reloaded.
  79. """
  80. if not self.has_source_access:
  81. raise RuntimeError(
  82. f"{type(self).__name__} cannot provide access to the source"
  83. )
  84. raise TemplateNotFound(template)
  85. def list_templates(self) -> t.List[str]:
  86. """Iterates over all templates. If the loader does not support that
  87. it should raise a :exc:`TypeError` which is the default behavior.
  88. """
  89. raise TypeError("this loader cannot iterate over all templates")
  90. @internalcode
  91. def load(
  92. self,
  93. environment: "Environment",
  94. name: str,
  95. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  96. ) -> "Template":
  97. """Loads a template. This method looks up the template in the cache
  98. or loads one by calling :meth:`get_source`. Subclasses should not
  99. override this method as loaders working on collections of other
  100. loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
  101. will not call this method but `get_source` directly.
  102. """
  103. code = None
  104. if globals is None:
  105. globals = {}
  106. # first we try to get the source for this template together
  107. # with the filename and the uptodate function.
  108. source, filename, uptodate = self.get_source(environment, name)
  109. # try to load the code from the bytecode cache if there is a
  110. # bytecode cache configured.
  111. bcc = environment.bytecode_cache
  112. if bcc is not None:
  113. bucket = bcc.get_bucket(environment, name, filename, source)
  114. code = bucket.code
  115. # if we don't have code so far (not cached, no longer up to
  116. # date) etc. we compile the template
  117. if code is None:
  118. code = environment.compile(source, name, filename)
  119. # if the bytecode cache is available and the bucket doesn't
  120. # have a code so far, we give the bucket the new code and put
  121. # it back to the bytecode cache.
  122. if bcc is not None and bucket.code is None:
  123. bucket.code = code
  124. bcc.set_bucket(bucket)
  125. return environment.template_class.from_code(
  126. environment, code, globals, uptodate
  127. )
  128. class FileSystemLoader(BaseLoader):
  129. """Load templates from a directory in the file system.
  130. The path can be relative or absolute. Relative paths are relative to
  131. the current working directory.
  132. .. code-block:: python
  133. loader = FileSystemLoader("templates")
  134. A list of paths can be given. The directories will be searched in
  135. order, stopping at the first matching template.
  136. .. code-block:: python
  137. loader = FileSystemLoader(["/override/templates", "/default/templates"])
  138. :param searchpath: A path, or list of paths, to the directory that
  139. contains the templates.
  140. :param encoding: Use this encoding to read the text from template
  141. files.
  142. :param followlinks: Follow symbolic links in the path.
  143. .. versionchanged:: 2.8
  144. Added the ``followlinks`` parameter.
  145. """
  146. def __init__(
  147. self,
  148. searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],
  149. encoding: str = "utf-8",
  150. followlinks: bool = False,
  151. ) -> None:
  152. if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
  153. searchpath = [searchpath]
  154. self.searchpath = [os.fspath(p) for p in searchpath]
  155. self.encoding = encoding
  156. self.followlinks = followlinks
  157. def get_source(
  158. self, environment: "Environment", template: str
  159. ) -> t.Tuple[str, str, t.Callable[[], bool]]:
  160. pieces = split_template_path(template)
  161. for searchpath in self.searchpath:
  162. # Use posixpath even on Windows to avoid "drive:" or UNC
  163. # segments breaking out of the search directory.
  164. filename = posixpath.join(searchpath, *pieces)
  165. f = open_if_exists(filename)
  166. if f is None:
  167. continue
  168. try:
  169. contents = f.read().decode(self.encoding)
  170. finally:
  171. f.close()
  172. mtime = os.path.getmtime(filename)
  173. def uptodate() -> bool:
  174. try:
  175. return os.path.getmtime(filename) == mtime
  176. except OSError:
  177. return False
  178. # Use normpath to convert Windows altsep to sep.
  179. return contents, os.path.normpath(filename), uptodate
  180. raise TemplateNotFound(template)
  181. def list_templates(self) -> t.List[str]:
  182. found = set()
  183. for searchpath in self.searchpath:
  184. walk_dir = os.walk(searchpath, followlinks=self.followlinks)
  185. for dirpath, _, filenames in walk_dir:
  186. for filename in filenames:
  187. template = (
  188. os.path.join(dirpath, filename)[len(searchpath) :]
  189. .strip(os.path.sep)
  190. .replace(os.path.sep, "/")
  191. )
  192. if template[:2] == "./":
  193. template = template[2:]
  194. if template not in found:
  195. found.add(template)
  196. return sorted(found)
  197. class PackageLoader(BaseLoader):
  198. """Load templates from a directory in a Python package.
  199. :param package_name: Import name of the package that contains the
  200. template directory.
  201. :param package_path: Directory within the imported package that
  202. contains the templates.
  203. :param encoding: Encoding of template files.
  204. The following example looks up templates in the ``pages`` directory
  205. within the ``project.ui`` package.
  206. .. code-block:: python
  207. loader = PackageLoader("project.ui", "pages")
  208. Only packages installed as directories (standard pip behavior) or
  209. zip/egg files (less common) are supported. The Python API for
  210. introspecting data in packages is too limited to support other
  211. installation methods the way this loader requires.
  212. There is limited support for :pep:`420` namespace packages. The
  213. template directory is assumed to only be in one namespace
  214. contributor. Zip files contributing to a namespace are not
  215. supported.
  216. .. versionchanged:: 3.0
  217. No longer uses ``setuptools`` as a dependency.
  218. .. versionchanged:: 3.0
  219. Limited PEP 420 namespace package support.
  220. """
  221. def __init__(
  222. self,
  223. package_name: str,
  224. package_path: "str" = "templates",
  225. encoding: str = "utf-8",
  226. ) -> None:
  227. package_path = os.path.normpath(package_path).rstrip(os.path.sep)
  228. # normpath preserves ".", which isn't valid in zip paths.
  229. if package_path == os.path.curdir:
  230. package_path = ""
  231. elif package_path[:2] == os.path.curdir + os.path.sep:
  232. package_path = package_path[2:]
  233. self.package_path = package_path
  234. self.package_name = package_name
  235. self.encoding = encoding
  236. # Make sure the package exists. This also makes namespace
  237. # packages work, otherwise get_loader returns None.
  238. import_module(package_name)
  239. spec = importlib.util.find_spec(package_name)
  240. assert spec is not None, "An import spec was not found for the package."
  241. loader = spec.loader
  242. assert loader is not None, "A loader was not found for the package."
  243. self._loader = loader
  244. self._archive = None
  245. template_root = None
  246. if isinstance(loader, zipimport.zipimporter):
  247. self._archive = loader.archive
  248. pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
  249. template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
  250. else:
  251. roots: t.List[str] = []
  252. # One element for regular packages, multiple for namespace
  253. # packages, or None for single module file.
  254. if spec.submodule_search_locations:
  255. roots.extend(spec.submodule_search_locations)
  256. # A single module file, use the parent directory instead.
  257. elif spec.origin is not None:
  258. roots.append(os.path.dirname(spec.origin))
  259. for root in roots:
  260. root = os.path.join(root, package_path)
  261. if os.path.isdir(root):
  262. template_root = root
  263. break
  264. if template_root is None:
  265. raise ValueError(
  266. f"The {package_name!r} package was not installed in a"
  267. " way that PackageLoader understands."
  268. )
  269. self._template_root = template_root
  270. def get_source(
  271. self, environment: "Environment", template: str
  272. ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
  273. # Use posixpath even on Windows to avoid "drive:" or UNC
  274. # segments breaking out of the search directory. Use normpath to
  275. # convert Windows altsep to sep.
  276. p = os.path.normpath(
  277. posixpath.join(self._template_root, *split_template_path(template))
  278. )
  279. up_to_date: t.Optional[t.Callable[[], bool]]
  280. if self._archive is None:
  281. # Package is a directory.
  282. if not os.path.isfile(p):
  283. raise TemplateNotFound(template)
  284. with open(p, "rb") as f:
  285. source = f.read()
  286. mtime = os.path.getmtime(p)
  287. def up_to_date() -> bool:
  288. return os.path.isfile(p) and os.path.getmtime(p) == mtime
  289. else:
  290. # Package is a zip file.
  291. try:
  292. source = self._loader.get_data(p) # type: ignore
  293. except OSError as e:
  294. raise TemplateNotFound(template) from e
  295. # Could use the zip's mtime for all template mtimes, but
  296. # would need to safely reload the module if it's out of
  297. # date, so just report it as always current.
  298. up_to_date = None
  299. return source.decode(self.encoding), p, up_to_date
  300. def list_templates(self) -> t.List[str]:
  301. results: t.List[str] = []
  302. if self._archive is None:
  303. # Package is a directory.
  304. offset = len(self._template_root)
  305. for dirpath, _, filenames in os.walk(self._template_root):
  306. dirpath = dirpath[offset:].lstrip(os.path.sep)
  307. results.extend(
  308. os.path.join(dirpath, name).replace(os.path.sep, "/")
  309. for name in filenames
  310. )
  311. else:
  312. if not hasattr(self._loader, "_files"):
  313. raise TypeError(
  314. "This zip import does not have the required"
  315. " metadata to list templates."
  316. )
  317. # Package is a zip file.
  318. prefix = (
  319. self._template_root[len(self._archive) :].lstrip(os.path.sep)
  320. + os.path.sep
  321. )
  322. offset = len(prefix)
  323. for name in self._loader._files.keys(): # type: ignore
  324. # Find names under the templates directory that aren't directories.
  325. if name.startswith(prefix) and name[-1] != os.path.sep:
  326. results.append(name[offset:].replace(os.path.sep, "/"))
  327. results.sort()
  328. return results
  329. class DictLoader(BaseLoader):
  330. """Loads a template from a Python dict mapping template names to
  331. template source. This loader is useful for unittesting:
  332. >>> loader = DictLoader({'index.html': 'source here'})
  333. Because auto reloading is rarely useful this is disabled per default.
  334. """
  335. def __init__(self, mapping: t.Mapping[str, str]) -> None:
  336. self.mapping = mapping
  337. def get_source(
  338. self, environment: "Environment", template: str
  339. ) -> t.Tuple[str, None, t.Callable[[], bool]]:
  340. if template in self.mapping:
  341. source = self.mapping[template]
  342. return source, None, lambda: source == self.mapping.get(template)
  343. raise TemplateNotFound(template)
  344. def list_templates(self) -> t.List[str]:
  345. return sorted(self.mapping)
  346. class FunctionLoader(BaseLoader):
  347. """A loader that is passed a function which does the loading. The
  348. function receives the name of the template and has to return either
  349. a string with the template source, a tuple in the form ``(source,
  350. filename, uptodatefunc)`` or `None` if the template does not exist.
  351. >>> def load_template(name):
  352. ... if name == 'index.html':
  353. ... return '...'
  354. ...
  355. >>> loader = FunctionLoader(load_template)
  356. The `uptodatefunc` is a function that is called if autoreload is enabled
  357. and has to return `True` if the template is still up to date. For more
  358. details have a look at :meth:`BaseLoader.get_source` which has the same
  359. return value.
  360. """
  361. def __init__(
  362. self,
  363. load_func: t.Callable[
  364. [str],
  365. t.Optional[
  366. t.Union[
  367. str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
  368. ]
  369. ],
  370. ],
  371. ) -> None:
  372. self.load_func = load_func
  373. def get_source(
  374. self, environment: "Environment", template: str
  375. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  376. rv = self.load_func(template)
  377. if rv is None:
  378. raise TemplateNotFound(template)
  379. if isinstance(rv, str):
  380. return rv, None, None
  381. return rv
  382. class PrefixLoader(BaseLoader):
  383. """A loader that is passed a dict of loaders where each loader is bound
  384. to a prefix. The prefix is delimited from the template by a slash per
  385. default, which can be changed by setting the `delimiter` argument to
  386. something else::
  387. loader = PrefixLoader({
  388. 'app1': PackageLoader('mypackage.app1'),
  389. 'app2': PackageLoader('mypackage.app2')
  390. })
  391. By loading ``'app1/index.html'`` the file from the app1 package is loaded,
  392. by loading ``'app2/index.html'`` the file from the second.
  393. """
  394. def __init__(
  395. self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
  396. ) -> None:
  397. self.mapping = mapping
  398. self.delimiter = delimiter
  399. def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
  400. try:
  401. prefix, name = template.split(self.delimiter, 1)
  402. loader = self.mapping[prefix]
  403. except (ValueError, KeyError) as e:
  404. raise TemplateNotFound(template) from e
  405. return loader, name
  406. def get_source(
  407. self, environment: "Environment", template: str
  408. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  409. loader, name = self.get_loader(template)
  410. try:
  411. return loader.get_source(environment, name)
  412. except TemplateNotFound as e:
  413. # re-raise the exception with the correct filename here.
  414. # (the one that includes the prefix)
  415. raise TemplateNotFound(template) from e
  416. @internalcode
  417. def load(
  418. self,
  419. environment: "Environment",
  420. name: str,
  421. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  422. ) -> "Template":
  423. loader, local_name = self.get_loader(name)
  424. try:
  425. return loader.load(environment, local_name, globals)
  426. except TemplateNotFound as e:
  427. # re-raise the exception with the correct filename here.
  428. # (the one that includes the prefix)
  429. raise TemplateNotFound(name) from e
  430. def list_templates(self) -> t.List[str]:
  431. result = []
  432. for prefix, loader in self.mapping.items():
  433. for template in loader.list_templates():
  434. result.append(prefix + self.delimiter + template)
  435. return result
  436. class ChoiceLoader(BaseLoader):
  437. """This loader works like the `PrefixLoader` just that no prefix is
  438. specified. If a template could not be found by one loader the next one
  439. is tried.
  440. >>> loader = ChoiceLoader([
  441. ... FileSystemLoader('/path/to/user/templates'),
  442. ... FileSystemLoader('/path/to/system/templates')
  443. ... ])
  444. This is useful if you want to allow users to override builtin templates
  445. from a different location.
  446. """
  447. def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
  448. self.loaders = loaders
  449. def get_source(
  450. self, environment: "Environment", template: str
  451. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  452. for loader in self.loaders:
  453. try:
  454. return loader.get_source(environment, template)
  455. except TemplateNotFound:
  456. pass
  457. raise TemplateNotFound(template)
  458. @internalcode
  459. def load(
  460. self,
  461. environment: "Environment",
  462. name: str,
  463. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  464. ) -> "Template":
  465. for loader in self.loaders:
  466. try:
  467. return loader.load(environment, name, globals)
  468. except TemplateNotFound:
  469. pass
  470. raise TemplateNotFound(name)
  471. def list_templates(self) -> t.List[str]:
  472. found = set()
  473. for loader in self.loaders:
  474. found.update(loader.list_templates())
  475. return sorted(found)
  476. class _TemplateModule(ModuleType):
  477. """Like a normal module but with support for weak references"""
  478. class ModuleLoader(BaseLoader):
  479. """This loader loads templates from precompiled templates.
  480. Example usage:
  481. >>> loader = ChoiceLoader([
  482. ... ModuleLoader('/path/to/compiled/templates'),
  483. ... FileSystemLoader('/path/to/templates')
  484. ... ])
  485. Templates can be precompiled with :meth:`Environment.compile_templates`.
  486. """
  487. has_source_access = False
  488. def __init__(
  489. self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]
  490. ) -> None:
  491. package_name = f"_jinja2_module_templates_{id(self):x}"
  492. # create a fake module that looks for the templates in the
  493. # path given.
  494. mod = _TemplateModule(package_name)
  495. if not isinstance(path, abc.Iterable) or isinstance(path, str):
  496. path = [path]
  497. mod.__path__ = [os.fspath(p) for p in path]
  498. sys.modules[package_name] = weakref.proxy(
  499. mod, lambda x: sys.modules.pop(package_name, None)
  500. )
  501. # the only strong reference, the sys.modules entry is weak
  502. # so that the garbage collector can remove it once the
  503. # loader that created it goes out of business.
  504. self.module = mod
  505. self.package_name = package_name
  506. @staticmethod
  507. def get_template_key(name: str) -> str:
  508. return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
  509. @staticmethod
  510. def get_module_filename(name: str) -> str:
  511. return ModuleLoader.get_template_key(name) + ".py"
  512. @internalcode
  513. def load(
  514. self,
  515. environment: "Environment",
  516. name: str,
  517. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  518. ) -> "Template":
  519. key = self.get_template_key(name)
  520. module = f"{self.package_name}.{key}"
  521. mod = getattr(self.module, module, None)
  522. if mod is None:
  523. try:
  524. mod = __import__(module, None, None, ["root"])
  525. except ImportError as e:
  526. raise TemplateNotFound(name) from e
  527. # remove the entry from sys.modules, we only want the attribute
  528. # on the module object we have stored on the loader.
  529. sys.modules.pop(module, None)
  530. if globals is None:
  531. globals = {}
  532. return environment.template_class.from_module_dict(
  533. environment, mod.__dict__, globals
  534. )